<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="TeamsForm" ref="formRef">
          <a-row>
						<a-col :span="24">
							<a-form-item label="团队名称" v-bind="validateInfos.teamName" id="TeamsForm-teamName" name="teamName">
								<a-input v-model:value="formData.teamName" placeholder="请输入团队名称" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品类型" v-bind="validateInfos.productType" id="TeamsForm-productType" name="productType">
								<a-input v-model:value="formData.productType" placeholder="请输入产品类型" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品名称" v-bind="validateInfos.productName" id="TeamsForm-productName" name="productName">
								<a-input v-model:value="formData.productName" placeholder="请输入产品名称" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="单位名称" v-bind="validateInfos.itemName" id="TeamsForm-itemName" name="itemName">
								<a-input v-model:value="formData.itemName" placeholder="请输入单位名称" :allow-clear="!disabled" />
							</a-form-item>
						</a-col>
						<!-- <a-col :span="24">
							<a-form-item label="子合同ID" v-bind="validateInfos.contractDetailInfoId" id="TeamsForm-contractDetailInfoId" name="contractDetailInfoId">
								<a-input v-model:value="formData.contractDetailInfoId" placeholder="请输入子合同ID" :allow-clear="!disabled" />
							</a-form-item>
						</a-col> -->

          </a-row>
        </a-form>
      </template>
    </JFormContainer>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated style="overflow:hidden;">
      <a-tab-pane tab="团队成员表" key="teamMembers" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="teamMembersTableRef"
          :loading="teamMembersTable.loading"
          :columns="teamMembersTable.columns"
          :dataSource="teamMembersTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :toolbarConfig="{ btns: ['remove', 'clearSelection'] }">
          <template #toolbar>
            <a-button v-if="!disabled" type="primary" @click="openAddMemberModal" v-auth="'teams:teams:addTeamMember'">新增</a-button>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <a-modal v-model:open="addMemberModalOpen" title="新增团队成员" @ok="handleAddMemberConfirm" @cancel="() => addMemberModalOpen = false" width="440px" bodyStyle="padding: 28px 36px; background: #fafbfc; border-radius: 10px;">
      <div style="display: flex; flex-direction: column; gap: 18px;">
        <div style="font-weight: bold; font-size: 16px; color: #333; margin-bottom: -6px;">基本信息</div>
        <a-select
          v-model:value="selectedMember"
          placeholder="请选择或输入成员姓名"
          style="width: 100%"
          :options="memberOptions"
          show-search
          :filter-option="false"
          @search="handleMemberSearch"
          @change="handleMemberChange"
          allow-clear
        />
        <a-select
          v-model:value="memberRole"
          placeholder="请选择任务角色"
          style="width: 100%"
          allow-clear
        >
          <a-select-option value="管理">管理</a-select-option>
          <a-select-option value="技术">技术</a-select-option>
        </a-select>
        <a-input v-model:value="productName" placeholder="产品名称（自动填充）" disabled />
        <a-textarea v-model:value="taskContent" placeholder="请输入任务内容" :rows="3" allow-clear />
        <a-input v-model:value="completion" placeholder="完成程度（默认：进行中）" disabled />
      </div>
    </a-modal>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryTeamMembersListByMainId, queryDataById, saveOrUpdate } from '../Teams.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {teamMembersColumns} from '../Teams.data';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { Form, Modal, message } from 'ant-design-vue';
  import { queryTeamMembers, saveOrUpdate as projectSaveOrUpdate, addTeamMember } from '../../projects/Projects.api';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "TeamsForm",
    components:{
      JVxeTable,
			JFormContainer,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const formRef = ref();
      const teamMembersTableRef = ref();
      const teamMembersTable = reactive<Record<string, any>>({
        loading: false,
        columns: teamMembersColumns,
        dataSource: []
      });
      const activeKey = ref('teamMembers');
      const formData = reactive<Record<string, any>>({
        id: '',
        teamName: '',
        productType: '',
        productName: '',
        itemName: '',
        contractDetailInfoId: '',
      });

      //表单验证
      const validatorRules = reactive({
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      const addMemberModalOpen = ref(false)
      const memberOptions = ref([])
      const allMemberOptions = ref([]) // 保存所有成员选项
      const selectedMember = ref(null)
      const selectedMemberInfo = ref(null)
      const memberRole = ref(null)
      const productName = ref('')
      const taskContent = ref('')
      const completion = ref('进行中') // 默认为进行中
      const memberSearchText = ref(''); // 搜索文本

      function add() {
        resetFields();
        teamMembersTable.dataSource = [];

      }

      async function edit(row) {

        //主表数据
        await queryMainData(row.id);
        //子表数据
        teamMembersTable.loading = true;
        try {
          const teamMembersDataList = await queryTeamMembersListByMainId(row['id']);
          if (Array.isArray(teamMembersDataList)) {
            // 处理数据库字段名映射
            const mappedData = teamMembersDataList.map(item => ({
              ...item,
              teamId: item.team_id || item.teamId,
              teamName: item.team_name || item.teamName,
              sysUserId: item.sys_user_id || item.sysUserId,
              productName: item.product_name || item.productName,
              createTime: item.create_time || item.createTime,
            }));
            teamMembersTable.dataSource = [...mappedData];
          } else {
            console.warn('获取团队成员列表返回格式异常:', teamMembersDataList);
            teamMembersTable.dataSource = [];
          }
        } catch (error) {
          console.error('获取团队成员列表失败:', error);
          message.error('获取团队成员列表失败');
          teamMembersTable.dataSource = [];
        } finally {
          teamMembersTable.loading = false;
        }
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        console.log('从数据库加载的团队数据:', row);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })

        // 处理数据库字段名映射
        if (row.team_name) {
          tmpData.teamName = row.team_name;
        }
        if (row.product_type) {
          tmpData.productType = row.product_type;
        }
        if (row.product_name) {
          tmpData.productName = row.product_name;
        }
        if (row.item_name) {
          tmpData.itemName = row.item_name;
        }
        if (row.contract_detail_info_id) {
          tmpData.contractDetailInfoId = row.contract_detail_info_id;
        }

        console.log('映射后的表单数据:', tmpData);
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'teamMembers': teamMembersTableRef,
      });

      async function getFormData() {
        try {
          // 触发表单验证
          await validate();
        } catch ({ errorFields }) {
          if (errorFields) {
            const firstField = errorFields[0];
            if (firstField) {
              formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            }
          }
          return Promise.reject(errorFields);
        }
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }



      async function openAddMemberModal() {
        addMemberModalOpen.value = true
        memberOptions.value = []
        allMemberOptions.value = []
        selectedMember.value = null
        memberRole.value = null
        taskContent.value = ''
        completion.value = '进行中' // 默认为进行中且不可修改

        // 自动填充产品名称（从团队表单数据中获取）
        productName.value = formData.productName || ''

        try {
          const res = await queryTeamMembers()
          console.log("获取团队成员列表结果:", res)

          if (Array.isArray(res)) {
            const options = res.map(item => ({
              label: item.realname || item.username || '未命名成员',
              value: item.id,
              raw: item
            }))
            memberOptions.value = options
            allMemberOptions.value = options // 保存所有选项用于搜索
          } else {
            message.warning('获取成员列表格式异常')
            console.warn('获取成员列表格式异常:', res)
          }

          if (memberOptions.value.length === 0) {
            message.info('暂无可选成员')
          }
        } catch (error) {
          console.error('获取成员列表失败:', error)
          message.error('获取成员列表失败')
        }
      }

      // 成员搜索处理
      function handleMemberSearch(value) {
        memberSearchText.value = value
        if (!value) {
          memberOptions.value = allMemberOptions.value
        } else {
          memberOptions.value = allMemberOptions.value.filter(option =>
            option.label.toLowerCase().includes(value.toLowerCase())
          )
        }
      }

      // 成员选择变化处理
      function handleMemberChange(value) {
        selectedMember.value = value
        // 如果是输入的值而不是选择的值，需要验证
        if (value && typeof value === 'string') {
          const foundMember = allMemberOptions.value.find(option =>
            option.label === value || option.value === value
          )
          if (!foundMember) {
            // 输入的成员不在列表中，清空选择
            selectedMember.value = null
            message.warning('输入的成员姓名不在可选列表中，请重新选择')
          }
        }
      }

      async function handleAddMemberConfirm() {
        if (!selectedMember.value) {
          message.warning('请选择成员')
          return
        }

        // 验证选择的成员是否在可选列表中
        const foundMember = allMemberOptions.value.find(opt =>
          opt.value === selectedMember.value || opt.label === selectedMember.value
        )
        if (!foundMember) {
          message.error('添加失败：输入的成员姓名不在可选列表中，请重新选择')
          return
        }

        // 获取完整成员信息
        selectedMemberInfo.value = foundMember.raw
        if (!selectedMemberInfo.value) {
          message.warning('无法获取成员信息')
          return
        }

        if(formData.id == ''){
          message.warning('请先保存团队信息')
          return
        }

        // 这里可以将成员信息加入表格或做后续处理
        addMemberModalOpen.value = false
        teamMembersTable.loading = true

        try {
          // 调用保存接口
          const member = selectedMemberInfo.value

          console.log("formData == ", formData)
          const payload = {
            teamName: formData.teamName, // 团队名
            teamId: formData.id, // 团队id
            name: member.realname, // 成员名
            sysUserId: member.id, // 成员ID（对应数据库字段sys_user_id）
            role: memberRole.value, // 任务角色
            productName: productName.value, // 产品名称
            task: taskContent.value, // 任务内容
            completion: completion.value, // 完成程度
          }
          console.log("准备加入的团队成员", payload)
          const result = await addTeamMember(payload)
          
          // 添加成功后，重新获取团队成员列表
          if (formData.id) {
            const teamMembersDataList = await queryTeamMembersListByMainId(formData.id)
            // 处理数据库字段名映射
            const mappedData = teamMembersDataList.map(item => ({
              ...item,
              teamId: item.team_id || item.teamId,
              teamName: item.team_name || item.teamName,
              sysUserId: item.sys_user_id || item.sysUserId,
              productName: item.product_name || item.productName,
              createTime: item.create_time || item.createTime,
            }));
            teamMembersTable.dataSource = [...mappedData]
          }
          
          // 清空选择
          selectedMember.value = null
          memberRole.value = null
          productName.value = ''
          taskContent.value = ''
          completion.value = ''
        } catch (e) {
          console.error('添加团队成员失败:', e)
          message.error('保存失败: ' + (e.message || '未知错误'))
        } finally {
          teamMembersTable.loading = false
        }
      }

      onMounted(() => {
        fetchTaskRoleOptions();
      });

      async function fetchTaskRoleOptions() {
        // 假设有统一的字典API
        const res = await defHttp.get({ url: '/sys/dict/getDictItems/task_role' });
        // 兼容不同返回结构
        //taskRoleOptions.value = Array.isArray(res) ? res.map(item => ({ label: item.text || item.label, value: item.value })) : [];
        taskRoleOptions.value = Array.isArray(res) ? res.map(item => ({ label: item.text || item.label, value: item.text || item.label })) : [];

      }



      return {
        teamMembersTableRef,
        teamMembersTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,

        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        addMemberModalOpen,
        memberOptions,
        selectedMember,
        selectedMemberInfo,
        openAddMemberModal,
        handleAddMemberConfirm,
        memberRole,
        productName,
        taskContent,
        completion,
        handleMemberSearch,
        handleMemberChange,
        allMemberOptions,
        memberSearchText,
      };
    },
  });
</script>
<style lang="less" scoped>
  .ant-tabs-tabpane.sub-one-form {
    max-height: 340px;
    overflow: auto;
  }
</style>
